<?php

/**
 * 简单皮尔森系数相关算法
 */
class SamplePearson {

    /**
     * 简单皮尔逊相关系数
     * @param array $first      第一组数据
     * @param array $second     第二组数据
     * @return float/int        相关系数 0.8-1.0 极强相关 0.6-0.8 强相关  0.4-0.6 中等程度相关  0.2-0.4 弱相关  0.0-0.2 极弱相关或无相关(负数逆相关)
     */
    public static function calculation_coefficient($first, $second) {
        if (count($first) !== count($second)) {
            return -1;
        }
        $first_vs = array_values($first);
        $second_vs = array_values($second);
        $firstAvg = array_sum($first_vs) / count($first_vs);
        $secondAvg = array_sum($second_vs) / count($second_vs);
        $a = 0;
        $bx = 0;
        $by = 0;
        for ($i = 0; $i < count($first_vs); $i++) {
            $xr = $first_vs[$i] - $firstAvg;
            $yr = $second_vs[$i] - $secondAvg;
            $a += $xr * $yr;
            $bx += pow($xr, 2); // 2次方
            $by += pow($yr, 2);
        }
        $b = sqrt($bx * $by); // 平方根
        return round($a / $b, 2);
    }

    /**
     * 匹配两个数组相似度
     * @param array $org
     * @param array $des
     * @return int|float
     */
    public static function match($org, $des) {
        if (empty($org) || empty($des) || !is_array($org) || !is_array($des) || count($org) != count($des)) {
            return 0;
        }

        $matchNum = 0;
        foreach ($org as $key => $item) {
            if ($des[$key] == $item) {
                $matchNum ++;
            }
        }
        return $matchNum / 10;
    }

}
